import util from '../../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    InputBottom: 0,
    chats: [],
    content: '',
    user: null,
    lover: null,
    scrollTop: 0
  },
  InputFocus(e) {
    this.setData({
      InputBottom: e.detail.height
    })
  },
  InputBlur(e) {
    this.setData({
      InputBottom: 0
    })
  },
  getchat(e) {
    this.data.content = e.detail.value
  },
  sendchat() {
    if (this.data.content == '') {
      wx.showToast({
        icon: "none",
        title: '消息不能为空',
      })
      return
    }
    var DATE = util.formatTime(new Date)
    const chat = {  // 用于前端显示该条数据
      _openid: this.data.user._openid,
      content: this.data.content,
      avatarurl: this.data.user.avatarurl,
      time: DATE,
      success: true
    }
    this.data.chats.push(chat)
    this.setData({
      content: '',
      chats: this.data.chats
    })
    wx.showLoading({
      title: "发送中"
    })
    wx.cloud.database().collection('chat').add({ //该条聊天记录保存到数据库
      data: {
        to_openid: this.data.lover._openid,
        content: chat.content,
        time: DATE,
        createtime: Date.parse(new Date())
      }
    }).then(res => {
      wx.hideLoading()
    }).catch(res => {
      wx.hideLoading()
      wx.showToast({
        icon: 'error',
        title: '发送失败',
      })
      this.data.chats.pop()
      chat.success = false
      this.data.chats.push(chat)
      this.setData({
        chats: this.data.chats
      })
    })
    this.backToBottom()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var user = wx.getStorageSync('user')
    var lover = wx.getStorageSync('lover')
    wx.cloud.callFunction({
      name: "getChats",
      data: {
        _openid: user._openid,
        skiplength: 0
      }
    }).then(res => {
      for (const item of res.result.list) {
        this.data.chats.push({
          _openid: item._openid,
          content: item.content,
          avatarurl: item.sendedBy[0].avatarurl,
          time: item.time,
          success: true
        })
      }
      this.data.chats.reverse()
      this.setData({
        user: user,
        lover: lover,
        chats: this.data.chats
      })
      this.backToBottom()
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var that = this
    wx.cloud.database().collection('chat').watch({
      onChange(snapshot) {
        if (snapshot.docChanges[0].dataType == 'add' && snapshot.docChanges[0].doc.to_openid == that.data.user._openid) {
          that.data.chats.push({
            _openid: snapshot.docChanges[0].doc._openid,
            content: snapshot.docChanges[0].doc.content,
            avatarurl: that.data.lover.avatarurl,
            time: snapshot.docChanges[0].doc.time,
            success: true
          })
          that.setData({
            chats: that.data.chats
          })
          that.backToBottom()
        }
      },
      onError(err) {
        console.error(err)
      }
    })
  },
  backToBottom() {
    let that = this;
    wx.createSelectorQuery().select('#viewCommunicationBody').boundingClientRect(function (rect) {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 100 // 滑动速度
      })
      that.setData({
        scrollTop: rect.height - that.data.scrollTop
      });
    }).exec();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showLoading({
      title: "加载数据中"
    })
    wx.cloud.callFunction({
      name: "getChats",
      data: {
        _openid: this.data.user._openid,
        skiplength: this.data.chats.length
      }
    }).then(res=>{
      if(res.result.list.length <= 0){
        wx.hideLoading()
        wx.stopPullDownRefresh()
        wx.showToast({
          icon: 'none',
          title: '没有更多数据啦',
        })
        return
      }
      var temp = []
      for (const item of res.result.list) {
       temp.push({
          _openid: item._openid,
          content: item.content,
          avatarurl: item.sendedBy[0].avatarurl,
          time: item.time,
          success: true
        })
      }
      temp.reverse()
      temp = temp.concat(this.data.chats)
      this.setData({
        chats: temp
      })
      wx.stopPullDownRefresh()
      wx.hideLoading()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})